package com.jdbc_.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

// 基于Druid连接池，实现连接池工具类
public class JDBCUtilsByDruid {
    private static DataSource dataSource;  // Druid数据库连接池对象

    // 在静态代码块完成dataSource初始化
    static {
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream("src\\druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);  // 相关参数在这里读取了（如url、user等）
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 连接方法
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();  // 返回连接
    }

    // 关闭方法 (不是真正关闭连接，只是把连接放回连接池)
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
